<template>
	<view>
		<scroll-view scroll-y="true" :style="{height:windowHeight}">
			<view class="">
				<view style="background-color: #ffffff;padding-left: 32rpx;padding-right: 32rpx;">
					<view style="height: 108rpx;display: flex;align-items: center;">
						<text class="title">客户名称<text class="star">*</text></text>
						<input type="text" v-model="name" placeholder="请填写客户名称" class="placeholder-view">
					</view>
					<view class="line"></view>
					<view style="height: 108rpx;display: flex;align-items: center;">
						<text class="title">客户简称</text>
						<input type="text" v-model="shortName" placeholder="请填写客户简称" class="placeholder-view">
					</view>
					<view class="line"></view>
					<view style="height: 108rpx;display: flex;align-items: center;">
						<text class="title">客户类型<text class="star">*</text></text>

						<view class="xuanze" @click="chooseCustomType">
							<text :class="customTypeId==-1 ? 'xuanze-t':'xuanze-tt'">{{customType}}</text>
							<image src="../../../../static/phone/quxuanze.png" class="xuanze-i"></image>
						</view>

					</view>
					<view class="line"></view>
					<view style="height: 108rpx;display: flex;align-items: center;">
						<text class="title">联系地址<text class="star">*</text></text>
						<input type="text" class="placeholder-view" placeholder="请填写联系地址" v-model="address">
						<!-- <picker mode="region" @change="bindRegionChange" style="margin-left: auto;">
							<view class="xuanze">
								<text
									:class="addressValue==-1 ? 'xuanze-t':'xuanze-tt'">{{addressValue==-1 ? '请选择':area}}</text>
								<image src="../../../../static/phone/quxuanze.png" class="xuanze-i"></image>
							</view>
						</picker> -->

					</view>
		<!-- 			<view class="line"></view>
					<view style="height: 108rpx;display: flex;align-items: center;">
						<input type="text" style="width: 686rpx;" class="placeholder-view" placeholder="请填写详细地址"
							v-model="address">
					</view> -->
					<view class="line"></view>
					<view style="height: 108rpx;display: flex;align-items: center;">
						<text class="title">绑定用户<text class="star">*</text></text>
						<input @input="searchCustomer" v-model="keywordCustomer" maxlength="11" placeholder="请输入用户手机号"
							class="placeholder-view">
					</view>

					<scroll-view scroll-y="true" class="laywer-sel-popup" v-if="searchCustomerList.length>0">
						<view v-for="(item,index) in searchCustomerList" :key="index" @click="clickCustomer(item)"
							style="height: 80rpx;display: flex;align-items: center;margin-left: 32rpx;">
							<image :src="item.account.avatarPic"
								v-if="item.account.avatarPic!=null && item.account.avatarPic!=undefined"
								style="width: 40rpx;height: 40rpx;margin-left: 8rpx;border-radius: 40rpx;"></image>

							<image src="../../../../static/phone/moren.png"
								v-if="item.account.avatarPic==null || item.account.avatarPic==undefined"
								style="width: 40rpx;height: 40rpx;margin-left: 8rpx;border-radius: 40rpx;"></image>
							<text class="listview-name" style="margin-left: 2rpx;">{{item.account.realName}}</text>
							<text class="listview-name" style="margin-left: 4rpx;">{{item.account.mobile}}</text>

						</view>
					</scroll-view>


					<view class="line"></view>



					<view class="listview">
						<view :class="index%2==1 ? 'main_item2':'main_item'" v-for="(item,index) in nameList">
							<image :src="item.account.avatarPic"
								v-if="item.account.avatarPic!=null && item.account.avatarPic!=undefined"
								style="width: 40rpx;height: 40rpx;margin-left: 8rpx;border-radius: 40rpx;"></image>

							<image src="../../../../static/phone/moren.png"
								v-if="item.account.avatarPic==null || item.account.avatarPic==undefined"
								style="width: 40rpx;height: 40rpx;margin-left: 8rpx;"></image>
							<text class="listview-name"
								style="margin-left: 2rpx;width: 100rpx;">{{item.account.realName}}</text>
							<text class="listview-name" style="margin-left: 4rpx;">{{item.account.mobile}}</text>
							<image @click="deleteIt(item,index)" src="../../../../static/phone/guanbi1.png"
								style="width: 32rpx;height: 32rpx;margin-left: auto;margin-right: 4rpx;"></image>
						</view>

					</view>

					<view class="line" v-if="nameList.length>0"></view>

				</view>
				<view style="margin-top:24rpx;background-color: #ffffff;padding-left: 32rpx;padding-right: 32rpx;">
					<view style="height: 108rpx;display: flex;align-items: center;">
						<text class="title">联系信息</text>
						<view style="margin-left: auto;display: flex;align-items: center;" @click="openClose">
							<text class="open-close">{{linkMsg? '收起':'展开'}}</text>
							<image :src="linkMsg ? zhankai:shouqi"
								style="margin-left: 5rpx;width: 24rpx;height: 24rpx;"></image>
						</view>
					</view>

					<view class="" v-if="linkMsg">
						<view class="line"></view>
						<view style="height: 108rpx;display: flex;align-items: center;">
							<text class="title">电话</text>
							<input type="text" v-model="phoneNumber" placeholder="请填写电话" class="placeholder-view">
						</view>
						<view class="line"></view>
						<view style="height: 108rpx;display: flex;align-items: center;">
							<text class="title">传真</text>
							<input type="text" v-model="faxNumber" placeholder="请填写传真" class="placeholder-view">
						</view>
						<view class="line"></view>
						<view style="height: 108rpx;display: flex;align-items: center;">
							<text class="title">邮箱</text>
							<input type="text" v-model="email" placeholder="请填写邮箱" class="placeholder-view">
						</view>
						<view class="line"></view>
						<view style="height: 108rpx;display: flex;align-items: center;">
							<text class="title">网站</text>
							<input type="text" v-model="website" placeholder="请填写网站" class="placeholder-view">
						</view>
						<view class="line"></view>
						<view style="height: 108rpx;display: flex;align-items: center;">
							<text class="title">联系人</text>
							<input type="text" v-model="contactName" placeholder="请填写联系人" class="placeholder-view">
						</view>
						<!-- <view class="line"></view> -->
					

					</view>
				</view>
				
				<view style="margin-top:24rpx;background-color: #ffffff;padding-left: 32rpx;padding-right: 32rpx;">
					<view style="height: 108rpx;display: flex;align-items: center;">
						<text class="title">所在地</text>
						<input type="text" v-model="domicile" placeholder="请填写所在地" class="placeholder-view">
					</view>
				</view>

				<view style="margin-top:24rpx;background-color: #ffffff;padding-left: 32rpx;padding-right: 32rpx;">
					<view style="height: 108rpx;display: flex;align-items: center;">
						<text class="title">开票信息</text>
						<view style="margin-left: auto;display: flex;align-items: center;" @click="openCloseKp">
							<text class="open-close">{{kpMsg? '收起':'展开'}}</text>
							<image :src="kpMsg ? zhankai:shouqi" style="margin-left: 5rpx;width: 24rpx;height: 24rpx;">
							</image>
						</view>
					</view>

					<view class="" v-if="kpMsg">
						<view class="line"></view>
						<view style="height: 108rpx;display: flex;align-items: center;">
							<text class="title">单位名称</text>
							<input type="text" v-model="companyName" placeholder="请填写单位名称" class="placeholder-view">
						</view>
						<view class="line"></view>
						<view style="height: 108rpx;display: flex;align-items: center;">
							<text class="title">纳税人识别号</text>
							<input type="text" v-model="taxNo" placeholder="请填写纳税人识别号" class="placeholder-view">
						</view>
						<view class="line"></view>
						<view style="height: 108rpx;display: flex;align-items: center;">
							<text class="title">开户银行</text>
							<input type="text" v-model="bankName" placeholder="请填写开户银行" class="placeholder-view">
						</view>
						<view class="line"></view>
						<view style="height: 108rpx;display: flex;align-items: center;">
							<text class="title">银行账号</text>
							<input type="text" v-model="bankNo" placeholder="请填写银行账号" class="placeholder-view">
						</view>
						<view class="line"></view>
						<view style="height: 108rpx;display: flex;align-items: center;">
							<text class="title">注册地址</text>
							<input type="text" v-model="regAddress" placeholder="请填写注册地址" class="placeholder-view">
						</view>
						<view class="line"></view>
						<view style="height: 108rpx;display: flex;align-items: center;">
							<text class="title">注册电话</text>
							<input type="text" v-model="regPhone" placeholder="请填写注册电话" class="placeholder-view">
						</view>
						<!-- <view class="line"></view>
						<view style="height: 108rpx;display: flex;align-items: center;">
							<text class="title">权限类别</text>
							<view class="xuanze" @click="chooseEnrollType">
								<text :class="enrollTypeId==-1 ? 'xuanze-t':'xuanze-tt'">{{enrollType}}</text>
								<image src="../../../../static/phone/quxuanze.png" class="xuanze-i"></image>
							</view>
						</view> -->
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="view-bottom">
			<view class="view-bottom-s">
				<view class="view-bottom-b" @click="addIt">
					确定
				</view>
			</view>
			<!-- <view style="height: 68rpx;background: #ffffff;" v-if="needAdapt"> -->
			<!-- 苹果x及以上的安全距离 -->
			<!-- </view> -->
		</view>
		<common-choose v-if="showChoose" :chooseList="chooseList" :chooseResult="chooseResult" :chooseTag="chooseTag"
			@gotIt="gotIt"></common-choose>
	</view>
</template>

<script>
	import commonChoose from '@/pages/phone/common/commonChoose.vue'
	import verify from '@/pages/utils/verifyUtils.js'
	let app = ''
	export default {
		components: {
			commonChoose
		},
		data() {
			return {
				role: '',
				roleUrl: '',
				windowHeight: 0,
				needAdapt: false, //判断是不是苹果x以上机型
				linkMsg: false,
				kpMsg: false,
				zhankai: require('../../../../static/phone/zhankai.png'),
				shouqi: require('../../../../static/phone/shouqi.png'),

				customType: '请选择客户类型',
				customTypeId: -1,
				enrollType: "请选择注册类别",
				enrollTypeId: -1,
				showChoose: false,
				chooseResult: '',
				chooseList: [],
				chooseTag: "",
				customTypeList: [],
				enrollTypeList: [],

				// addressValue: -1,

				nameList: [],


				name: '',
				shortName: '',
				categoryDict: '',
				// area: '',
				address: '',
				// province: '',
				// city: '',
				// county: '',
				domicile: '',
				phoneNumber: '',
				faxNumber: '',
				eMail: '',
				website: '',
				contactName: '',
				companyName: '',
				taxNo: '',
				bankName: '',
				bankNo: '',
				regAddress: '',
				regPhone: '',
				permDict: '',


				keywordCustomer: '',
				searchCustomerList: [],

				price: '',
				goodsId: '',
				goodsName: '',

				userInfo: null,
			}
		},
		onLoad(options) {
			app = getApp()
			var _this = this
			_this.needAdapt = app.globalData.needAdapt && app.globalData.isIPhone
			if (_this.needAdapt) {
				_this.windowHeight = (app.globalData.windowHeight - 88) * 2 + 'rpx'
			} else {
				_this.windowHeight = (app.globalData.windowHeight - 54) * 2 + 'rpx'
			}

			_this.role = app.globalData.role
			_this.roleUrl = _this.$roleUrl({
				tab: _this.role
			})

			_this.price = Number.parseInt(options.price)
			_this.goodsId = options.goodsId
			_this.goodsName = options.goodsName

			//获取用户类型
			_this.getCustomer_type()
			//获取权限类别
			// _this.getCustomer_perm()
		},
		onShow() {
			//现将创建者 放在绑定用户里
			let userInfo = app.globalData.userInfo
			this.userInfo = userInfo
			let avatarPic = userInfo.avatarPic
			console.log('avatarPic',avatarPic)
			if(avatarPic.indexOf('http')<0){
				avatarPic = this.$imageUrls({picUrls: avatarPic})
			}
			let account = {
				avatarPic: avatarPic,
				realName: userInfo.realName,
				mobile: userInfo.mobile,
				id:userInfo.accId

			}
			let item = {
				account: account,
				id: userInfo.userId,
				accId:userInfo.accId
			}
			this.nameList.push(item)
			

		},
		mounted() {

		},
		methods: {
			showToastEmpty(val) {
				uni.showToast({
					title: `${val}不能为空！`,
					icon: 'none'
				})
			},

			/**
			 * 获取客户类型
			 */
			async getCustomer_type() {
				let _this = this
				const res = await _this.$myRequest({
					url: "/comm/dict/list/param_customer_type",
				})
				console.log('客户类型', res)
				if (res.data.code == 200) {
					let list = res.data.data
					_this.customTypeList = list
				}
			},
			/**
			 * 获取权限类别
			 */
			async getCustomer_perm() {
				let _this = this
				const res = await _this.$myRequest({
					url: "/comm/dict/list/param_customer_perm",
				})
				console.log('权限类别', res)
				if (res.data.code == 200) {
					let list = res.data.data
					_this.enrollTypeList = list

				}
			},

			/**
			 * 选择客户类型 弹窗
			 */
			chooseCustomType() {
				let _this = this
				if (_this.customTypeList.length == 0) {
					uni.showToast({
						title: '暂无客户类型',
						icon: 'none'
					})
					return
				}
				_this.chooseTag = 'customType'
				_this.chooseList = _this.customTypeList
				_this.chooseResult = _this.customType
				_this.$nextTick(() => {
					_this.showChoose = true
				})

			},
			/**
			 * @param {Object} 选择注册类别
			 */
			chooseEnrollType() {
				let _this = this
				if (_this.customTypeList.length == 0) {
					uni.showToast({
						title: '暂无注册类别',
						icon: 'none'
					})
					return
				}
				_this.chooseTag = 'enroll'
				_this.chooseList = _this.enrollTypeList
				_this.chooseResult = _this.enrollType
				_this.$nextTick(() => {
					_this.showChoose = true
				})

			},

			/**
			 * 选择后赋值
			 */
			gotIt(val) {
				console.log(val)
				let _this = this
				_this.showChoose = false
				let tag = val.split(";")[0]
				let index = val.split(";")[1]
				if (tag == 'customType') {
					_this.categoryDict = _this.customTypeList[index]['value']
					_this.customType = _this.customTypeList[index]['name']
					_this.customTypeId = _this.customTypeList[index]['id']
				} else if (tag == 'enroll') {
					_this.permDict = _this.enrollTypeList[index]['value']
					_this.enrollType = _this.enrollTypeList[index]['name']
					_this.enrollTypeId = _this.enrollTypeList[index]['id']
				}
			},
			/**
			 * 省市区选择
			 */
			// bindRegionChange(val) {
			// 	console.log(val)
			// 	let _this = this
			// 	_this.area = val.detail.value[0] + ' ' + val.detail.value[1] + ' ' + val.detail.value[2]

			// 	_this.addressValue = val.detail.code[0]

			// 	_this.province = val.detail.value[0]
			// 	_this.city = val.detail.value[1]
			// 	_this.county = val.detail.value[2]
			// },
			/**
			 * 点击了确定
			 */
			addIt() {
				let _this = this

				if (!verify.isNotEmpty(_this.name)) {
					_this.showToastEmpty('客户名称')
					return
				}

				if (!verify.isNotEmpty(_this.categoryDict)) {
					_this.showToastEmpty('客户类型')
					return
				}
				// if (!verify.isNotEmpty(_this.area)) {
				// 	_this.showToastEmpty('联系地址')
				// 	return
				// }
				if (!verify.isNotEmpty(_this.address)) {
					_this.showToastEmpty('联系地址')
					return
				}

				if (_this.nameList.length == 0) {
					_this.showToastEmpty('绑定用户')
					return
				}
				_this.saveIt()
			},

			async saveIt() {
				let _this = this
				uni.showToast({
					title: '正在提交...',
					icon: 'loading'
				})
				let data = {
					name: _this.name,
					shortName: _this.shortName,
					categoryDict: _this.categoryDict,
					// province: _this.province,
					// city: _this.city,
					// county: _this.county,
					address: _this.address,
					domicile: _this.domicile,
					phoneNumber: _this.phoneNumber,
					faxNumber: _this.faxNumber,
					email: _this.email,
					website: _this.website,
					contactName: _this.contactName,
					companyName: _this.companyName,
					taxNo: _this.taxNo,
					bankName: _this.bankName,
					bankNo: _this.bankNo,
					regAddress: _this.regAddress,
					regPhone: _this.regPhone,
					permDict: _this.permDict,
				}

				let userIds = []
				for (var i = 0; i < _this.nameList.length; i++) {
					userIds.push(_this.nameList[i]['id'])
				}
				_this.$set(data, 'userIds', userIds);
				
				//创建者本人 默认为绑定用户 且已授权
				let authorizeUserIds = []
				authorizeUserIds.push(this.userInfo.userId)
				_this.$set(data, 'authorizeUserIds', authorizeUserIds);
				
				

				const res = await _this.$myRequest({
					url: `/${_this.roleUrl}/customer`,
					method: 'POST',
					data: data
				})
				uni.hideLoading()
				console.log('提交结果', res)
				if (res.data.code == 200) {
					uni.showToast({
						title: '客户添加成功',
						icon: 'success',
						duration: 2000
					})
					_this.buyIt(res.data.data.id, res.data.data.name)

				} else {
					uni.showToast({
						title: res.data.msg,
						duration: 2000
					})
				}
			},

			async buyIt(id, name) {
				let _this = this
				uni.showLoading({
					title: "正在提交订单..."
				})
				let data = {
					goodsId: _this.goodsId,
					goodsName: _this.goodsName,
					custId: id,
					custName: name,
					orderAmt: _this.price,
					buyerId: app.globalData.userInfo.userId
				}

				const res = await _this.$myRequest({
					url: `/${_this.roleUrl}/goodsOrder`,
					method: 'POST', //默认是GET
					data: data,
				})
				uni.hideLoading()
				console.log('订单提交结果', res)
				if (res.data.code == 200) {
					_this.payIt(res.data.data.tradeId)
				}
			},
			/**
			 * 支付
			 */
			async payIt(id) {
				let _this = this
				uni.showLoading({
					title: "正在支付..."
				})
			
				const res = await _this.$myRequest({
					url:`/wx/pay/create?tradeId=${id}`,
					method:'POST',//默认是GET
					// data:data,
				})
			
				uni.hideLoading()
				console.log('支付结果', res)
				if (res.data.code == 200) {
					
					uni.requestPayment({
						"timeStamp":res.data.data.timeStamp,
						"nonceStr": res.data.data.nonceStr,
						"package": res.data.data.packageValue,
						"signType": res.data.data.signType,
						"paySign": res.data.data.paySign,
						success: (payres) => {
							console.log('微信支付成功结果',payres)
							if(payres.errMsg==='requestPayment:ok'){
								uni.showToast({
									title:'购买成功!',
									icon:'success'
								})
								setTimeout(function() {
									uni.navigateBack({
										delta: -1
									})
								}, 1500);
							}
						},
						fail: (payerr) => {
							console.log('微信支付失败结果',payerr)
							uni.showToast({
								title: payerr
							})
						}
					})
					
				} else {
					uni.showToast({
						title: res.data.msg
					})
				}
			},

			/**
			 * 绑定用户
			 */
			searchCustomer(val) {
				console.log(val)
				let _this = this
				let code = val.detail.value
				//查询律师选择器
				_this.getCustomerNameList(code)
			},
			async getCustomerNameList(code) {
				let _this = this
				const res = await _this.$myRequest({
					url: `/${_this.roleUrl}/commUser/selector/0`,
					data: {
						keyword: code,
						size: 1000,
						page: 1
					},
					method: 'POST', //默认是GET
				})
				// console.log('用户', res)
				_this.searchCustomerList = []
				if (res.data.code == 200) {
					let list = res.data.data
					for (var i = 0; i < list.length; i++) {
						let avatarPic = list[i]['account']['avatarPic']
						if(avatarPic!=undefined && avatarPic.indexOf('http')<0){
							avatarPic = this.$imageUrls({picUrls: avatarPic})
							list[i]['account']['avatarPic']= avatarPic
						}
						
					}
					_this.searchCustomerList = list
				}
			},
			clickCustomer(item) {
				console.log(item)
				console.log(this.nameList)
				let _this = this
				for (var i = 0; i < _this.nameList.length; i++) {
					if (item.account.id == _this.nameList[i]['account'].id) {
						uni.showToast({
							title: '当前用户已存在!',
							icon: 'none'
						})

						return
					}
				}

				this.nameList.push(item)
				this.searchCustomerList = []
				this.keywordCustomer = ''
			},

			/**
			 * 联系信息展开收起
			 */
			openClose() {
				this.linkMsg = !this.linkMsg
			},
			/**
			 * 开票信息展开收起
			 */
			openCloseKp() {
				this.kpMsg = !this.kpMsg
			},


			deleteIt(item, index) {
				console.log('删除', item)
				if (item.id === this.userInfo.userId) {
					uni.showModal({
						title: '提示',
						content: '创建者本人无法删除',
						showCancel: false,

					})
					return
				}
				this.nameList.splice(index, 1)
			},
		}
	}
</script>

<style>
	page {
		background-color: #f7f7f7;
	}
</style>
<style lang="scss" scoped>
	.view-bottom {
		position: fixed;
		width: 100%;
		bottom: 0;
		background-color: #ffffff;
		border-top: 1rpx #eeeeee solid;
		padding-bottom: env(safe-area-inset-bottom); // 适配iphoneX的底部
	}

	.view-bottom-s {
		height: 108rpx;
		display: flex;
		align-items: center;
	}

	.view-bottom-b {
		width: 686rpx;
		height: 88rpx;
		background: #2DA9C5;
		border-radius: 58rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 36rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 500;
		color: #E8F7FB;
		line-height: 50rpx;
		margin-left: 32rpx;
	}

	.title {
		font-size: 28rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 550;
		color: #333333;
	}

	.star {
		color: #FF6132;
	}

	.line {
		height: 1rpx;
		background-color: #eeeeee;
	}

	.line2 {
		height: 24rpx;
		background-color: #f7f7f7;
	}

	.placeholder-view {
		font-size: 28rpx;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #333333;
		margin-left: auto;
		text-align: right;
		width: 500rpx;
	}

	.open-close {
		font-size: 24rpx;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #2DA9C5;
	}

	.xuanze {
		margin-left: auto;
		display: flex;
		align-items: center;
	}

	.xuanze-t {
		font-size: 28rpx;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #888888;
		margin-right: 5rpx;
	}

	.xuanze-tt {
		font-size: 28rpx;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #333333;
		margin-right: 5rpx;
	}

	.xuanze-i {
		width: 12rpx;
		height: 24rpx;
	}

	.listview {
		display: flex;
		flex-wrap: wrap;
		padding-bottom: 32rpx;

	}


	.main_item {
		width: 336rpx;
		height: 88rpx;
		background: #E8F7FB;
		border-radius: 8rpx;
		display: flex;
		align-items: center;
		margin-top: 16rpx;
	}

	.main_item2 {
		width: 336rpx;
		height: 88rpx;
		background: #E8F7FB;
		border-radius: 8rpx;
		display: flex;
		align-items: center;
		margin-top: 16rpx;
		margin-left: 14rpx;
	}

	.listview-name {
		font-size: 24rpx;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #666666;
	}

	.laywer-sel-popup {
		height: 330rpx;
		width: 686rpx;
		background: #FFFFFF;
		box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.2);
		border-radius: 2px;
	}
</style>
